package com.woniu.teachmall04.controller;

import com.woniu.teachmall04.entity.Goods;
import com.woniu.teachmall04.service.GoodsService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class IndexController {
    @Autowired
    private GoodsService goodsService;

    @RequestMapping("/")
    public String index(Model model, HttpSession session,
                        @RequestParam(defaultValue = "1") int page) {

        // 检查用户登录状态
        if(session.getAttribute("loginUser") != null) {
            model.addAttribute("loginUser", session.getAttribute("loginUser"));

            // 获取总记录数
            long total = goodsService.count();

            // 计算总页数
            int totalPages = (int) Math.ceil((double) total / GoodsService.PAGE_SIZE);

            // 确保页码在有效范围内
            if (page < 1) page = 1;
            if (page > totalPages && totalPages > 0) page = totalPages;

            // 获取当前页的数据 - 这里改为使用findByPage方法
            List<Goods> goodsList = goodsService.findByPage(page, GoodsService.PAGE_SIZE);

            // 添加分页相关属性到模型
            model.addAttribute("goodsList", goodsList);
            model.addAttribute("currentPage", page);
            model.addAttribute("totalPages", totalPages);
            model.addAttribute("total", total);

            return "index";
        } else {
            return "login";
        }
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/register")
    public String register() {
        return "register";
    }

    @GetMapping("/admin")
    public String admin() {
        return "admin";
    }
}